#define _CRT_SECURE_NO_WARNINGS 1class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        int m = matrix.size();
        int n = matrix[0].size();
        int l = 0, r = n - 1;
        int up = 0, down = m - 1;
        int num = n * m;
        vector<int> ans;
        while (num)
        {
            for (int i = l; i <= r; i++)ans.push_back(matrix[up][i]);
            up++;
            num -= (r - l + 1);
            if (num <= 0)break;
            for (int i = up; i <= down; i++)ans.push_back(matrix[i][r]);
            r--;
            num -= (down - up + 1);
            if (num <= 0)break;

            for (int i = r; i >= l; i--)ans.push_back(matrix[down][i]);
            down--;
            num -= (r - l + 1);
            if (num <= 0)break;

            for (int i = down; i >= up; i--)ans.push_back(matrix[i][l]);
            l++;
            num -= (down - up + 1);
            if (num <= 0)break;
        }
        return ans;
    }
};